package cae.gui.file;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import cae.gui.util.CaeAlert;
import cae.gui.util.CaeJDialog;
import cae.logic.CaeMessageSender;
import cae.logic.destination.CaeDestination;
import cae.logic.destination.CaeDestinatiosManager;
import cae.logic.file.CaeFileSender;


public class CaeSendFileDialog extends CaeJDialog implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JPanel panel = null;
	
	private JComboBox nick;
	private JTextField directory;
	private File sFile;
	private static Logger logger = Logger.getLogger(CaeSendFileDialog.class);
	
	public CaeSendFileDialog(JFrame frame, boolean modal)
	{
		
		super(frame, "Enviar Archivo: ", modal);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		
		panel = new JPanel();
		getContentPane().add(panel);
		
		panel.setLayout( new GridBagLayout() );
		GridBagConstraints destConst = new GridBagConstraints();
		destConst.insets = new Insets(5,5,5,5);
		destConst.anchor = GridBagConstraints.WEST;
		destConst.fill = GridBagConstraints.HORIZONTAL;
		
		destConst.gridx = 0;
		destConst.gridy = 0;
		panel.add(new JLabel("Destinatario: "), destConst);
		
		destConst.gridx = 1;
		destConst.gridy = 0;
		destConst.gridwidth = 3;
		List<CaeDestination> dests = CaeDestinatiosManager.getInstance().getDestinations();
		Object[] o = new Object[dests.size()];
		for (int i = 0; i < dests.size(); i++) {
			o[i] = dests.get(i).getAlias();
		}
		nick = new JComboBox(o);
		nick.setMinimumSize(new Dimension(200, 22));
		nick.setMaximumSize(new Dimension(200, 22));
		nick.setPreferredSize(new Dimension(200, 22));
		panel.add(nick, destConst);
		
		destConst.gridx = 0;
		destConst.gridy = 1;
		destConst.gridwidth = 1;
		panel.add(new JLabel("Archivo: "), destConst);
		
		destConst.gridx = 1;
		destConst.gridy = 1;
		destConst.gridwidth = 1;
		directory = new JTextField();
		directory.setMinimumSize(new Dimension(400, 22));
		directory.setMaximumSize(new Dimension(400, 22));
		directory.setPreferredSize(new Dimension(400, 22));
		directory.setEditable(false);
		panel.add(directory, destConst);

		destConst.gridx = 2;
		destConst.gridy = 1;
		destConst.gridwidth = 1;
		JButton button = new JButton("...");
		panel.add(button, destConst);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				JFileChooser chooser = new JFileChooser("C:/");
				int returnVal = chooser.showOpenDialog(panel);
				if(returnVal == JFileChooser.APPROVE_OPTION) 
				{
					sFile = chooser.getSelectedFile();
					directory.setText(sFile.getAbsolutePath());
				}
			}	
		});
		
		destConst.gridx = 2;
		destConst.gridy = 3;
		
		JButton add = new JButton("Enviar");
		add.addActionListener(this);
		panel.add(add, destConst);
		
		pack();
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(screenSize.width / 4, screenSize.height /4);
        
		setResizable(false);
		setAlwaysOnTop(true);
		setVisible(true);
		
		// TODO FOCO
		//FocusManager.getCurrentManager().
		
	}

	public void actionPerformed(ActionEvent e)
	{
		if(sFile == null)
		{
			CaeAlert.error("Debe seleccionar un archivo ", this);
			return;
		}
		
		new Thread(new Runnable(){

			public void run() {
				
				CaeDestination dest = CaeDestinatiosManager.getInstance().getDestinationByAlias((String) nick.getSelectedItem());
				
				try
				{
					CaeFileSender.sendFile(sFile.getAbsolutePath(), sFile.getName(), dest);
					CaeAlert.info("Archivo "+ sFile.getName() +" enviado correctamente", panel);
					
					// NOTIFICACION DE ENVIO AL DESTINATARIO
					try {
						CaeMessageSender.sendMessage("Archivo " + sFile.getName() + " recibido", dest);
					} catch (IOException e) {
						logger.info("No se pudo enviar la notificacion de envio del archivo " + sFile.getName(), e );
					}
				}
				catch(Exception e)
				{
					CaeAlert.error("Error al enviar el archivo, " + sFile.getAbsolutePath()+ " "+ e, panel);
					logger.error("Error al enviar el archivo, " + sFile.getAbsolutePath(), e);
				}
			}
		}).start();
		
		setVisible(false);
	}
	
}
